﻿using UnityEditor;
using UnityEngine;

namespace EditorFramework
{
    public class FolderField : GUIBase
    {
        public string Path => mPath;
        public string Folder;
        public string Title;
        public string DefaultName;
        protected string mPath = "Assets";
        
        public FolderField(string path="Assets", string folder="Assets", string title="Select Folder", string defaultName="default name")
        {
            mPath = path;
            Folder = folder;
            Title = title;
            DefaultName = defaultName;
        }
        public override void OnGUI(Rect rect)
        {
            base.OnGUI(rect);
            
            var rects = rect.VerticalSplit(rect.width - 30);
            Rect leftRect = rects[0];
            Rect rightRect = rects[1];

            bool currentGUIEnabled = GUI.enabled;
            GUI.enabled = false;
            EditorGUI.TextField(leftRect, mPath);
            GUI.enabled = currentGUIEnabled;
            
            if (GUI.Button(rightRect, GUIContents.Folder))
            {
                var path = EditorUtility.OpenFolderPanel(Title, Folder, DefaultName);

                if (!string.IsNullOrEmpty(path) && path.IsDirectory())
                {
                    mPath = path.ToAssetsPath();
                    Debug.Log(mPath);
                }
            }

            var dragInfo = DragAndDropTool.Drag(Event.current, rightRect);
            if (dragInfo.EnterArea && !dragInfo.Dragging && dragInfo.Complete && dragInfo.Paths[0].IsDirectory())
            {
                mPath = dragInfo.Paths[0];
            }
        }

        public void SetPath(string path)
        {
            mPath = path;
        }
        
        protected override void OnDispose()
        {
            
        }
    }
}